# Read and write mobile phone messages
# 读写手机的信息，及相关配置，
__author__ = 'daqiao'


import os
from adbutils._device import BaseDevice
from phones.conf import phones
from conf_json_rw import json_read, json_write

# 以下是数据存储的数据格式的示例，以后根据需求再扩展，
# json example,
example_phone = {
    "serial": {
        "device_name": "自定义名称或者手机对外型号，"
    }
}

phones_path = r".\phones"
# # 将相对路径转换为绝对路径
# absolute_path = os.path.abspath(phones_path)
phones_info_path = os.path.join(phones_path, "phones_info.json")


def get_device_name(device: BaseDevice):
    """
    从phone_conf.json 中通过序列号获取 手机的自定义名称，方便识别，
    :param device:
    :return:
    """
    serial = device.serial
    brand = device.shell('getprop ro.product.brand')
    model = brand + " " + device.prop.model
    phones_info_dict = {}
    # 先判断是否存在phone_conf.json文件，
    if os.path.exists(phones_info_path):
        stat = os.stat(phones_info_path)
        if stat.st_size > 0:  # 如果文件大小大于0，那么文件存在
            # print("文件存在")
            data = json_read(phones_info_path)
            # 如果有文件，判断文件中是否有对应的信息，
            if serial in data:
                return data[serial]["device_name"]
            else:
                # 如果没有信息，则获取手机的对外型号后 写入，并返回，
                phones_info_dict.update(data)
    # 如果没有，获取手机的对外型号后创建，
    print("文件不存在")
    external_model = phones.get(model, model)
    phones_info_dict[serial] = {"device_name": external_model}
    json_write(phones_info_path, phones_info_dict)
    return external_model


def update_device_name(device: BaseDevice, device_name):
    """
    更新phone_conf.json
    :return:
    """
    serial = device.serial
    data = json_read(phones_info_path)
    data[serial] = {"device_name": device_name}
    json_write(phones_info_path, data)
    print("更新手机的 自定义名称 device_name")


if __name__ == '__main__':
    from adbutils import adb

    devices_list = adb.device_list()
    for d in devices_list:
        device_name = get_device_name(d)
        print(device_name)
        # update_device_name(d, "我的手机1")
        # device_name = get_device_name(d)
        # print(device_name)
